<template>
  <div
    :class="isShowBox1 ? 'cmt-container1' : 'cmt-container2'"
    ref="cmtRef"
    >
    <!-- 评论列表 -->
    <div class="cmt-list">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了!"
        :immediate-check="false"
        offset="50"
        @load="handleLoad"
        >
        <!-- 评论的 Item 项 -->
        <div
          class="cmt-item"
          v-for="item in cmtList"
          :key="item.com_id"
          >
          <!-- 头部区域 -->
          <div class="cmt-header">
            <!-- 头部左侧 -->
            <div class="cmt-header-left">
              <img :src="item.aut_photo" class="avatar">
              <span class="uname">{{ item.aut_name }}</span>
            </div>
            <!-- 头部右侧 -->
            <div class="cmt-header-right">
              <van-icon
                name="like"
                size="16"
                color="red"
                v-if="item.is_liking"
                @click="handleCmtLikeOrUnlike(false, item)"
              />
              <van-icon
                name="like-o"
                size="16"
                color="gray"
                v-else
                @click="handleCmtLikeOrUnlike(true, item)"
                />
            </div>
          </div>
          <!-- 主体区域 -->
          <div class="cmt-body">
            {{ item.content }}
          </div>
          <!-- 尾部区域 -->
          <div class="cmt-footer">{{ $timeAgo(item.pubdate) }}</div>
        </div>
      </van-list>
    </div>

    <!-- 底部添加评论区域 - 1 -->
    <div
      class="add-cmt-box van-hairline--top"
      v-if="isShowBox1">
      <van-icon name="arrow-left" size="0.48rem" @click="$router.back()" />
      <div class="ipt-cmt-div" @click="isShowBox1 = false">发表评论</div>
      <div class="icon-box">
        <van-badge :content="totalCount" :max="99">
          <van-icon
            name="comment-o"
            size="0.53333334rem"
            @click="handleScroll"
            />
        </van-badge>
        <van-icon name="star-o" size="0.53333334rem" />
        <van-icon name="share-o" size="0.53333334rem" />
      </div>
    </div>

    <!-- 底部添加评论区域 - 2 -->
    <div
      class="cmt-box van-hairline--top"
      v-else>
      <textarea
        placeholder="友善评论、理性发言、阳光心灵"
        v-focus
        @blur="handleBlur"
        v-model.trim="content"
        @keydown.enter="handlePulish"
      ></textarea>
      <van-button
        type="default"
        :disabled="!content"
        @click="handlePulish">发布</van-button>
    </div>
  </div>
</template>

<script>
import {
  getCmtListAPI,
  likeCmtAPI,
  unlikeCmtAPI,
  publishCmtAPI
} from '@/api/article'
export default {
  name: 'CommentList',
  data () {
    return {
      // 评论列表
      cmtList: [],
      // 评论数量
      totalCount: 0,
      // 控制评论第1个盒子的显示
      isShowBox1: true,
      // 评论内容
      content: '',
      loading: false,
      finished: false
    }
  },
  created () {
    this.getCmtList()
  },
  methods: {
    // 获取评论列表
    async getCmtList () {
      // 调接口发请求
      const resp = await getCmtListAPI(this.$route.query.aid, this.lastId || null, 10)
      // 解构
      const { results, total_count: totalCount, last_id: lastId } = resp.data
      // 如果后台没有数据了
      if (!results.length) {
        // 整个列表加载结束
        this.finished = true
        return
      }
      // 赋值
      this.cmtList = [...this.cmtList, ...results]
      this.totalCount = totalCount || ''
      this.lastId = lastId
      // 更新loading状态为false
      this.loading = false
    },
    // 评论点赞或取赞
    async handleCmtLikeOrUnlike (flag, obj) {
      // flag是true表示点赞；否则是取赞
      try {
        // 调接口发请求(把点赞状态保存到数据库)
        flag ? await likeCmtAPI(obj.com_id) : await unlikeCmtAPI(obj.com_id)
        // 直接把对应的评论对象中的 is_liking 取反
        obj.is_liking = !obj.is_liking
        // 成功的提示文字
        flag
          ? this.$toast.success('点赞成功')
          : this.$toast.success('取赞成功')
      } catch (e) {
        // 失败的提示文字
        flag
          ? this.$toast.fail('点赞失败')
          : this.$toast.fail('取赞失败')
      }
    },
    // 点击评论图标滑动
    handleScroll () {
      // 需求：点击评论图标让评论列表盒子出现在可视区
      // 方式1： 利用 offsetTop + document.documentElement.scrollTop/window.scrollTo(x, y)
      // window.scrollTo(0, this.$refs.cmtRef.offsetTop)
      // 或
      // document.documentElement.scrollTop = this.$refs.cmtRef.offsetTop
      // 方式2： 找到评论组件的根元素 + 调用scrollIntoView方法

      // 1. 获取评论组件的根元素
      const el = this.$refs.cmtRef
      // 2. 调用scrollIntoView方法
      el.scrollIntoView({
        // 添加滚动动画
        behavior: 'smooth'
      })
    },
    // 发表评论
    async handlePulish () {
      // 非空检验
      if (!this.content) return
      // 调接口发请求
      const resp = await publishCmtAPI(this.$route.query.aid, this.content)
      // 把后台返回的新的评论对象unshift到cmtList数组中
      this.cmtList.unshift(resp.data.new_obj)
      // 评论数量++
      this.totalCount++
      // 清空文本域的内容
      this.content = ''
      // 隐藏评论的第2套盒子
      this.isShowBox1 = true
    },
    // 文本域失焦
    handleBlur () {
      // 异步设置 isShowBox1 为 true
      setTimeout(() => {
        this.isShowBox1 = true
      })
    },
    // 上拉加载
    handleLoad () {
      this.getCmtList()
    }
  }
}
</script>

<style scoped lang="less">
.cmt-list {
  padding: 10px;
  .cmt-item {
    padding: 15px 0;
    + .cmt-item {
      border-top: 1px solid #f8f8f8;
    }
    .cmt-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .cmt-header-left {
        display: flex;
        align-items: center;
        .avatar {
          width: 40px;
          height: 40px;
          background-color: #f8f8f8;
          border-radius: 50%;
          margin-right: 15px;
        }
        .uname {
          font-size: 12px;
        }
      }
    }
    .cmt-body {
      font-size: 14px;
      line-height: 28px;
      text-indent: 2em;
      margin-top: 6px;
      word-break: break-all;
    }
    .cmt-footer {
      font-size: 12px;
      color: gray;
      margin-top: 10px;
    }
  }
}

.cmt-container1 {
  padding-bottom: 46px;
}
.cmt-container2 {
  padding-bottom: 80px;
}

// 发布评论的盒子 - 1
.add-cmt-box {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  box-sizing: border-box;
  background-color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 46px;
  line-height: 46px;
  padding-left: 10px;
  .ipt-cmt-div {
    flex: 1;
    border: 1px solid #efefef;
    border-radius: 15px;
    height: 30px;
    font-size: 12px;
    line-height: 30px;
    padding-left: 15px;
    margin-left: 10px;
    background-color: #f8f8f8;
  }
  .icon-box {
    width: 40%;
    display: flex;
    justify-content: space-evenly;
    line-height: 0;
  }
}

.child {
  width: 20px;
  height: 20px;
  background: #f2f3f5;
}

// 发布评论的盒子 - 2
.cmt-box {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 80px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  padding-left: 10px;
  box-sizing: border-box;
  background-color: white;
  textarea {
    flex: 1;
    height: 66%;
    border: 1px solid #efefef;
    background-color: #f8f8f8;
    resize: none;
    border-radius: 6px;
    padding: 5px;
  }
  .van-button {
    height: 100%;
    border: none;
  }
}

</style>
